var tableName = 'rmp';//本地存储表名
var version = 2.0;//用于更新本地缓存配置


var userKey = top.userKey;
var maxHeight = $(document).height();
var maxWidth = $(document).width();
/**
 * 自定义layui扩展模块
 */
layui.config({
    base: '/rmp/js/ext/'
});

/**
 * 请求url
 */


var VALIDATE_USER_KEY_URL = '/rmp/mock/login.json';
var LIST_USER_SPACE_INFO_URL = '/rmp/mock/listUserSpace.json';
var GET_USER_SPACE_SETTING_URL = '/rmp/mock/getUserSetting.json';


var SERVER_INFO_LIST_ALL_URL = '../mock/listAllServerInfo.json';
var SERVER_INFO_LIST_PAGE_URL = '../mock/pageListServerInfo.json';
var SERVER_INFO_DEL_URL = '../mock/delServer.json';
var SERVER_INFO_EDIT_URL = '../mock/editServer.json';
var SERVER_INFO_MONITORING_URL = '../mock/monitoringServer.json';
var SERVER_INFO_BATCH_SAVE_URL = '../mock/batchSave.json';

var MONITORING_SERVER_LIST_URL = 'getList.json';


/**
 * 默认标记css className
 */
var DYNAMIC_DATA_CLASS = "dynamic-data"; //动态数据
var SERVER_CONNECT_STATUS_CLASS = "server-connect-status";//链接状态标记
var SERVER_ACTION_BAR_BTN_RECONNECT_CLASS = "rpm-monitoring-btn-reconnect";//重连
var SERVER_ACTION_BAR_BTN_DEL_CLASS = "rpm-monitoring-btn-del";//删除按钮


//通用Datatables配置
var DT_CONSTANT = {
    DATA_TABLES : {
        DEFAULT_OPTION:{
            "aaSorting": [[ 1, "asc" ]],//默认第几个排序
            "bStateSave": true,//状态保存
            "processing": false,   //显示处理状态
            "serverSide": false,  //服务器处理
            "autoWidth": false,   //自动宽度
            "scrollX": true,
            "lengthChange": true,
            "paging": true,
            "language": {
                "url": "../plugins/zh_CN.json"
            },
            "lengthMenu": [[10, 20, 50, 100], ['10', '20', '50', '100']],  //显示数量设置
            "initComplete": function(settings, json){ //多选框的设置
                $("th > input[type='checkbox']:eq(0)").click(function() {
                    if ($(this).is(":checked")) {
                        $(this).parents('.dataTables_wrapper').find("td > input[type='checkbox']").prop("checked", true);
                    } else {
                        $(this).parents('.dataTables_wrapper').find("td > input[type='checkbox']").prop("checked", false);
                    }
                });
            }
        },
        //常用的COLUMN render
        COLUMNFUN:{
            //过长内容省略号替代
            ELLIPSIS:function (data, type, row, meta) {
                data = data||"";
                return '<span title="' + data + '" class="layui-elip">' + data + '</span>';
            },
            TAGS:function(data, type, row, meta){
                var arrs = data.split(" ");
                var html = '';
                $.each(arrs, function(i, n) {
                    html += '<span class="layui-badge layui-bg-green rmp-server-info-tags-label">' + n + '</span>&nbsp;';

                });
                return html;
            }
        },
        //html渲染工具
        RENDERUTIL:{
            DYNAMIC_DATA:function(dataId, dataItem, dataName, data){
                return '<span class="' + DYNAMIC_DATA_CLASS + ' layui-bg-blue" data-id="'
                    + dataId + '" data-item="' + dataItem + '" data-name="' + dataName + '">&nbsp;'
                    + data + '&nbsp;</span>';
            },
            CONNECT_STATUS:function(connectStatus){
                if (connectStatus != "true") {
                    return '<a href="javascript:;" onclick="javascript:layer.alert(\'' + connectStatus + '\',{icon:5});">' +
                        '<span class="layui-badge ' + SERVER_CONNECT_STATUS_CLASS + '">异常</span></a>';
                }
                return '<span class="layui-badge layui-bg-green ' + SERVER_CONNECT_STATUS_CLASS + '">正常</span>';
            },
            ACTION_BAR:function(dataId, serverType, btns){
                var html = '';
                $.each(btns, function(className, text){
                    html += '<button type="button" class="layui-btn layui-btn-danger layui-btn-sm ' + className + '" server-type="' + serverType + '" data-id="' + dataId + '">' + text + '</button>';
                });
                return html;
            }
        }
    }
};


/**
 * 提前定义好不同类型服务器信息<br>
 * 通过该配置使用JS渲染页面
 */
var serverInfos = {
    //可供选择的类型，在服务器管理模块使用
    serverTypes:{
        linux:"Linux",
        weblogic:"Weblogic"
    },
    //可以监控视图上显示的类型,视图显示已在此定义的类型为准
    viewTypes:{
        linux:"Linux",
        weblogic:"Weblogic"
/*        weblogic:"Weblogic",
        jvm:"JVM",
        tomcat:"Tomcat",
        nginx:"Nginx",
        redis:"Redis",
        mongodb:"MongoDB",
        dubbo:"Dubbo"*/
    },
    linux:{
        additionalParameters:{ //附加参数设置
            javaHome:{
                mark:'javaHome_binPath',
                placeholder:'java的安装目录bin完整路径',
                defaultValue:'/opt/jdk1.7/bin'
            }
        },
        //dt初始化参数
        dtInitParameter:{
            ajax:{
                url:"../mock/linux/" + MONITORING_SERVER_LIST_URL,
                data:{userKey:userKey}
            },
            paging:false,
            columnDefs: [{"orderable":false, "aTargets":[0, 4, 20]}],
            columns:[
                {
                    "data": null,
                    "render": function(data) {
                        return '<input type="checkbox">';
                    }
                },
                {
                    "data":"viewId"
                },
                {
                    "data":null,
                    "render":function(data, type, full, meta) {
                        return data.host + ":" + data.port;
                    }
                },
                {
                    "data":"realHost"
                },
                {
                    "data":"tags",
                    "render":DT_CONSTANT.DATA_TABLES.COLUMNFUN.TAGS
                },
                {
                    "data":"username"
                },
                {
                    "data":"cpuInfo",
                    "render":function(data) {
                        return data + "核";
                    }
                },
                {
                    "data":"memInfo",
                    "render":function(data) {
                        return data + "kb";
                    }
                },
                {
                    "data":"info.diskInfo.userDisk",
                    "render":function(data) {
                        return DT_CONSTANT.DATA_TABLES.RENDERUTIL.DYNAMIC_DATA(data.viewId, "diskInfo", "userDisk", data + "%");
                    }
                },
                {
                    "data":"info.diskInfo.rootDisk",
                    "render":function(data) {
                        return DT_CONSTANT.DATA_TABLES.RENDERUTIL.DYNAMIC_DATA(data.viewId, "diskInfo", "rootDisk", data + "%");
                    }
                },
                {
                    "data":null,
                    "render":function(data) {
                        return DT_CONSTANT.DATA_TABLES.RENDERUTIL.DYNAMIC_DATA(data.viewId, "commonInfo", "freeCpu", data.info.freeCpu + "%");
                    }
                },
                {
                    "data":null,
                    "render":function(data) {
                        return DT_CONSTANT.DATA_TABLES.RENDERUTIL.DYNAMIC_DATA(data.viewId, "commonInfo", "freeMem", data.info.freeMem + "%");
                    }
                },
                {
                    "data":null,
                    "render":function(data) {
                        return DT_CONSTANT.DATA_TABLES.RENDERUTIL.DYNAMIC_DATA(data.viewId, "tcpInfo", "ESTABLISHED", data.info.tcpInfo.ESTABLISHED);
                    }
                },
                {
                    "data":null,
                    "render":function(data) {
                        return DT_CONSTANT.DATA_TABLES.RENDERUTIL.DYNAMIC_DATA(data.viewId, "tcpInfo", "CLOSE_WAIT", data.info.tcpInfo.CLOSE_WAIT);
                    }
                },
                {
                    "data":null,
                    "render":function(data) {
                        return DT_CONSTANT.DATA_TABLES.RENDERUTIL.DYNAMIC_DATA(data.viewId, "tcpInfo", "TIME_WAIT", data.info.tcpInfo.TIME_WAIT);
                    }
                },
                {
                    "data":null,
                    "render":function(data) {
                        return DT_CONSTANT.DATA_TABLES.RENDERUTIL.DYNAMIC_DATA(data.viewId, "tcpInfo", "LISTEN", data.info.tcpInfo.LISTEN);
                    }
                },
                {
                    "data":null,
                    "render":function(data) {
                        return DT_CONSTANT.DATA_TABLES.RENDERUTIL.DYNAMIC_DATA(data.viewId, "networkInfo", "rx", data.info.networkInfo.rx + "kb/s");
                    }
                },
                {
                    "data":null,
                    "render":function(data) {
                        return DT_CONSTANT.DATA_TABLES.RENDERUTIL.DYNAMIC_DATA(data.viewId, "networkInfo", "tx", data.info.networkInfo.tx + "kb/s");
                    }
                },
                {
                    "data":null,
                    "render":function(data) {
                        return DT_CONSTANT.DATA_TABLES.RENDERUTIL.DYNAMIC_DATA(data.viewId, "commonInfo", "ioWait", data.info.ioWait + "%");
                    }
                },
                {
                    "data":"connectStatus",
                    "render":function(data) {
                        return DT_CONSTANT.DATA_TABLES.RENDERUTIL.CONNECT_STATUS(data);
                    }
                },
                {
                    "data":null,
                    "render":function(data) {
                        return DT_CONSTANT.DATA_TABLES.RENDERUTIL.ACTION_BAR(data.viewId, "linux", {
                            SERVER_ACTION_BAR_BTN_DEL_CLASS:"删除",
                            SERVER_ACTION_BAR_BTN_RECONNECT_CLASS:"重连"
                        });
                    }
                }
            ]
        },
        //表头列设定
        tableColumn:{
            "1":"ID",
            "2":"HOST",
            "3":"真实HOST",
            "4":"标签",
            "5":"用户名",
            "6":"CPU核数",
            "7":"内存大小",
            "8":"磁盘空间<br>用户目录",
            "9":"磁盘空间<br>根目录",
            "10":"实时空闲CPU",
            "11":"实时空闲内存",
            "12":"TCP连接<br>ESTABLISHED",
            "13":"TCP连接<br>CLOSE_WAIT",
            "14":"TCP连接<br>TIME_WAIT",
            "15":"TCP连接<br>LISTEN",
            "16":"入网带宽",
            "17":"出网带宽",
            "18":"io等待",
            "19":"连接状态",
            "20":"操作"
        },
        //表头上方工具栏设定 只限button
        btnTool:[
            {
                size:'sm',
                type:'default',
                text:'命令控制台',
                id:"rmp-monitoring-linux-console"
            }
        ],
        //预警信息值设定
        alertSettingValue:{
            freeCpu:{
                value:10,
                sign:"%",
                mode:"<"
            },
            freeMem:{
                value:10,
                sign:"%",
                mode:"<"
            },
            userDisk:{
                value:90,
                sign:"%",
                mode:">"
            },
            ioWait:{
                value:20,
                sign:"%",
                mode:">"
            },
            TIME_WAIT:{
                value:40000,
                sign:"",
                mode:">"
            },
            CLOSE_WAIT:{
                value:40000,
                sign:"",
                mode:">"
            }
        },
        //对应常量解释
        constant:{
            ESTABLISHED:"Tcp连接-ESTABLISHED",
            CLOSE_WAIT:"Tcp连接-CLOSE_WAIT",
            LISTEN:"Tcp连接-LISTEN",
            TIME_WAIT:"Tcp连接-TIME_WAIT",
            rx:"入网总流量[kb/s]",
            tx:"出网总流量[kb/s]",
            rootDisk:"根目录磁盘已使用百分比[%]",
            userDisk:"用户目录磁盘已使用百分比[%]",
            freeCpu:"空闲CPU百分比[%]",
            freeMem:"空闲内存百分比[%]",
            ioWait:"io等待CPU执行时间百分比[%]"
        },
        //类型属性定义
        propertyObject:{
            commonInfo:{
                freeCpu:[],
                freeMem:[],
                ioWait:[]
            },
            tcpInfo:{
                ESTABLISHED:[],
                LISTEN:[],
                CLOSE_WAIT:[],
                TIME_WAIT:[]
            },
            networkInfo:{
                rx:[],
                tx:[]
            },
            diskInfo:{
                rootDisk:[],
                userDisk:[]
            }
        }

    },
    weblogic:{
        additionalParameters:{
            javaHome:{
                mark:'javaHome_binPath',
                placeholder:'java的安装目录bin完整路径',
                defaultValue:'/opt/jdk1.7/bin'
            },
            linuxLoginUsername:{
                mark:'主机账号',
                placeholder:'对应主机的登录账号',
                defaultValue:''
            },
            linuxLoginPassword:{
                mark:'主机密码',
                placeholder:'对应主机的登录密码',
                defaultValue:''
            },
            startScriptPath:{
                mark:'启动脚本路径',
                placeholder:'该weblogic的启动脚本完整路径',
                defaultValue:''
            }
        },
        dtInitParameter:{
            ajax:{
                url:"../mock/weblogic/" + MONITORING_SERVER_LIST_URL,
                data:{userKey:userKey}
            },
            paging:false,
            columnDefs: [{"orderable":false, "aTargets":[0, 4, 19, 20, 21, 22, 23, 25]}],
            columns:[
                {
                    "data": null,
                    "render": function(data) {
                        return '<input type="checkbox">';
                    }
                },
                {
                    "data":"viewId"
                },
                {
                    "data":null,
                    "render":function(data, type, full, meta) {
                        return data.host + ":" + data.port;
                    }
                },
                {
                    "data":"realHost"
                },
                {
                    "data":"tags",
                    "render":DT_CONSTANT.DATA_TABLES.COLUMNFUN.TAGS
                },
                {
                    "data":"username"
                },
                {
                   "data" :"serverName"
                },
                {
                    "data" :"info.runStatus"
                },
                {
                    "data" :"info.health"
                },
                {
                    "data" :"startTime"
                },
                {
                    "data" :"maxJvm"
                },
                {
                    "data" :"info.jvmInfo.currentSize"
                },
                {
                    "data" :"info.jvmInfo.freeSize"
                },
                {
                    "data" :"info.jvmInfo.freePercent"
                },
                {
                    "data" :"maxThreadCount"
                },
                {
                    "data" :"info.queueInfo.pendingCount"
                },
                {
                    "data" :"info.queueInfo.idleCount"
                },
                {
                    "data" :"info.queueInfo.hoggingThreadCount"
                },
                {
                    "data" :"info.queueInfo.throughput"
                },
                {
                    "data" :"info.jdbcInfo" //jdbcState
                },
                {
                    "data" :"info.jdbcInfo"  //activeConnectionsCurrentCount
                },
                {
                    "data" :"info.jdbcInfo" //availableConnectionCount
                },
                {
                    "data" :"info.jdbcInfo"  //waitingForConnectionCurrentCount
                },
                {
                    "data" :"info.jdbcInfo"  //activeConnectionsHighCount
                },
                {
                    "data":"connectStatus",
                    "render":function(data) {
                        return DT_CONSTANT.DATA_TABLES.RENDERUTIL.CONNECT_STATUS(data);
                    }
                },
                {
                    "data":null,
                    "render":function(data) {
                        return DT_CONSTANT.DATA_TABLES.RENDERUTIL.ACTION_BAR(data.viewId, "weblogic", {
                            SERVER_ACTION_BAR_BTN_DEL_CLASS:"删除",
                            SERVER_ACTION_BAR_BTN_RECONNECT_CLASS:"重连"
                        });
                    }
                }
            ]
        },
        tableColumn:{
            "1":"ID",
            "2":"HOST",
            "3":"真实HOST",
            "4":"标签",
            "5":"用户名",
            "6":"节点名",
            "7":"运行状态",
            "8":"健康度",
            "9":"启动时间",
            "10":"JVM堆<br>最大值",
            "11":"JVM堆<br>当前使用",
            "12":"JVM堆<br>当前空闲",
            "13":"JVM堆<br>空闲百分比",
            "14":"活动线程总数",
            "15":"暂挂用户数",
            "16":"空闲线程数",
            "17":"独占线程数",
            "18":"吞吐量",
            "19":"JDBC当前<br>状态",
            "20":"JDBC当前<br>活动连接数",
            "21":"JDBC当前<br>可用连接数",
            "22":"JDBC当前<br>等待连接数",
            "23":"JDBC历史<br>最大连接数",
            "24":"连接状态",
            "25":"操作"
        },
        btnTool:[],
        alertSettingValue:{
            freePercent:{
                value:10,
                sign:"%",
                mode:"<"
            },
            pendingCount:{
                value:1,
                sign:"",
                mode:">"
            },
            waitingForConnectionCurrentCount:{
                value:1,
                sign:"",
                mode:">"
            },
            waitingForConnectionCurrentCount:{
                value:1,
                sign:"",
                mode:">"
            }
        },
        constant:{
            currentSize:"JVM堆当前使用大小[MB]",
            freeSize:"JVM堆当前空闲大小[MB]",
            freePercent:"JVM堆当前空闲百分比[%]",
            maxThreadCount:"活动线程总数",
            pendingCount:"暂挂用户请求数",
            idleCount:"空闲线程数",
            activeConnectionsCurrentCount:"JDBC当前活动连接数",
            availableConnectionCount:"JDBC当前可用连接数",
            waitingForConnectionCurrentCount:"JDBC当前等待连接数",
            hoggingThreadCount:"独占线程数",
            throughput:"吞吐量",
            activeConnectionsHighCount:"JDBC历史最大活动连接数"
        },
        propertyObject:{
            commonInfo:{
            },
            jvmInfo:{
                currentSize:[],
                freeSize:[],
                freePercent:[]
            },
            queueInfo:{
                maxThreadCount:[],
                pendingCount:[],
                idleCount:[],
                throughput:[],
                hoggingThreadCount:[]
            },
            jdbcInfo:{
                jdbcState:{},
                activeConnectionsCurrentCount:{},
                availableConnectionCount:{},
                waitingForConnectionCurrentCount:{},
                activeConnectionsHighCount:{}
            }
        }
    },
    jvm:{
        additionalParameters:{ //附加参数设置
            javaHome:{
                mark:'javaHome_binPath',
                placeholder:'java的安装目录bin完整路径',
                defaultValue:'/opt/jdk1.7/bin'
            }
        }
    }
};


/*********************************全局公共方法*******************************************/
/**
 * 验证返回值
 * @param json
 * @param callback
 */
function validatReturnJson(json, successCallback){
    if (json.returnCode == 0) {
        successCallback != null && successCallback();
    } else {
        layer.alert(json.msg == null ? "系统错误,请重试!" : json.msg, {icon:5});
    }
}

/**
 * 验证userKey
 * @param userKey
 */
function validateUserKey(userKey, hrefFlag) {
    $.post(VALIDATE_USER_KEY_URL, {userKey:userKey}, function(json){
        validatReturnJson(json, function(){
            if (hrefFlag) {
                window.location.href = 'html/index.html';
            }
            layui.data('rmp', {
                key:'userKey',
                value:json.data.userKey
            });
        })
    });
}


/**
 * 批量操作方法
 * @param url   url 远程操作接口
 * @param table   对应Datatables实例
 * @param opName 操作方式名称 默认为 删除
 * @param idName 对应实体的ID名称
 * @param textName 名称的属性名
 * @param otherSendData 其他要随着ID发送的参数
 * @returns {Boolean}
 */
function batchOp (url, opName, table, idName, textName, otherSendData, callback) {
    var checkdata =  $(table.table().container()).find("td > input:checked");
    if (checkdata.length < 1) {
        return false;
    }

    if (opName == null) {
        opName = "删除";
    }
    layer.confirm('确认' + opName + '选中的' + checkdata.length + '条记录?', {icon:0, title:'警告'}, function(index) {
        layer.close(index);
        var loadindex = layer.msg('正在进行批量' + opName + "...", {icon:16, time:60000, shade:0.35});
        var delCount = 0;
        var totalCount = 0;
        var errorTip = "";
        $.each(checkdata ,function(i, n) {
            var d = table.row($(n).parents('tr')).data();
            var objId = d[idName];//获取id
            var objName = d[textName];	//name属性为对象的名称
            var params = {id: objId};
            params[idName] = objId;//兼容id和实体对应的idName两种获取方式
            if (otherSendData != null && otherSendData instanceof Object) {
                $.each(otherSendData, function(i, n) {
                    params[i] = n;
                });
            }

            //layer.msg("正在" + opName + objName + "...", {time: 999999});
            $.ajax({
                type:"post",
                url:url,
                data:params,
                //async:false,
                success:function(data) {
                    totalCount++;
                    if(data.returnCode != 0) {
                        errorTip += "[" + objName + "]<br>";
                    }else{
                        table.row($(n).parents('tr')).remove().draw();
                        delCount++;
                    }
                }
            });
        });

        var intervalID = setInterval(function() {
            if (totalCount == checkdata.length) {
                clearInterval(intervalID);
                if (callback != null) {
                    callback();
                }
                layer.close(loadindex);
                if (errorTip != "") {
                    errorTip = "在" + opName + "<br>" + errorTip + "时发生了错误<br>请执行单笔" + opName + "操作!";
                    layer.alert(errorTip, {icon:5}, function(index) {
                        layer.close(index);
                        layer.msg("共" + opName + delCount + "条数据!", {icon:1, time:2000});
                    });
                } else {
                    layer.msg("共" + opName + delCount + "条数据!", {icon:1, time:2000});
                }
            }
        }, 500);
    });
}

/**
 * 批量以代理的方式绑定监听事件
 * @param configs
 * @returns {$}
 */
$.fn.delegates = function(configs) {
    el = $(this[0]);
    for (var name in configs) {
        var value = configs[name];
        if (typeof value == 'function') {
            var obj = {};
            obj.click = value;
            value = obj;
        };
        for (var type in value) {
            el.delegate(name, type, value[type]);
        }
    }
    return this;
};

/**
 * 快速创建layer弹出层
 * 参数解释
 * @param title 标题
 * @param url  url地址或者html页面
 * @param w 宽度,默认值
 * @param h 高度,默认值
 * @param type 类型 1-页面层 2-frame层
 * @param success 成功打开之后的回调函数
 * @param cancel 右上角关闭层的回调函数
 * @param end 层销毁之后的回调
 * @param other 其他DT设置
 * @returns index
 */
function layer_show (title, url, w, h, type, success, cancel, end, other) {
    if (other == null) {
        other = {};
    }

    if (title == null || title == '') {
        title = false;
    };
    if (url == null || url == '') {
        url="404.html";
    };
    if (w == null || w == '' || w >= maxWidth) {//设置最大宽度
        w =	maxWidth * 0.9
    };
    if (h == null || h == '' || h >= maxHeight) {//设置最大高度
        h= (maxHeight * 0.86) ;
    };
    if (type == null || type == '') {
        type = 2;
    }
    index = layer.open($.extend(true, {
        type: type,
        area: [w + 'px', h + 'px'],
        fix: false, //不固定
        maxmin: false,
        shade:0.4,
        anim:5,
        shadeClose:true,
        title: title,
        content: url,
        success:success,
        cancel:cancel,
        end:end
    } ,other));
    return index;
}
/**
 * layui本地存储 存入数据
 */
function saveLocalData(key, value) {
    if (typeof value == 'object') {
        value = JSON.stringify(value);
    }
    layui.data(tableName, {
        key: key
        ,value: value
    });
}

/**
 * layui本地存储 取出数据
 */
function getLocalData(key, parse) {
    var table = layui.data(tableName);
    var value = table != null ? table[key] : null;
    if (parse && value != null) {
        value = JSON.parse(value);
    }
    return value;
}

/**
 * layui 本地存储 删除数据
 */
function delLocalData(key) {
    layui.data(tableName, {
        key:key,
        remove:true
    });
}
